# -*- coding: utf-8 -*-
# @Time    : 2023.09.01 15:56
# @Author  : _oah
# @File    : YH_spi_opt_params.py
# @Description : TODO
import logging
from datetime import datetime, date

import flask_restful
from flask_restful import Resource, reqparse
import numpy as np
import pandas as pd
import time
import utils
import json

# 自定义模块
from errors import my_abort, ResponseCode

# 自定义错误
flask_restful.abort = my_abort
root_logger = logging.getLogger('root')
logger = logging.getLogger('main')
# =============================================================================

# =============================================================================
# 模型import
from .spi_of_opt import function


# =============================================================================


class YH_spi_opt_params(Resource):
    def __init__(self):
        # Authorization, fileId
        self.parser = reqparse.RequestParser(bundle_errors=True)
        self.parser.add_argument('Authorization', type=str, required=True, help="需要数据文件绝对路径")
        self.parser.add_argument('id', type=str, required=True, help="需要数据文件绝对路径")

    def post(self):
        currentTimeStr = utils.nowTimeText4China()
        print('=== 工期预测开始, 中国时间: %s' % currentTimeStr)

        computeDurationStart = time.time()
        httpStatusCode = 200
        queryParams = self.parser.parse_args()
        # 获取参数，根据参数需求增删
        # Authorization, fileId
        Authorization = queryParams.get('Authorization')
        id = queryParams.get('id')


        logger.info('=== 工期预测请求 ==> GET ?\nAuthorization=%s\nid=%s' % (Authorization, id))
        res = function(Authorization, id)

        if res['resp_code'] == ResponseCode.WRONG_PARAM:
            httpStatusCode = 400
        computeDuration = time.time() - computeDurationStart
        logger.info('=== 工期预测 ==> 耗时( %.3f 秒 )' % computeDuration)
        return res, httpStatusCode, {"Content-Type": "application/json; charset=utf-8"}


class NpEncoder(json.JSONEncoder):  # 继承json.JSONEncoder
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.float):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        elif isinstance(obj, pd.Timestamp):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, date):
            return obj.strftime('%Y-%m-%d')
        elif isinstance(obj, np.datetime64):
            return np.datetime_as_string(obj)
        else:
            return super(NpEncoder, self).default(obj)
